<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数:{{ total }} 条</span>
        </template>

        <template #right>
          <el-button v-if="checkBtnPermission('POINT_EXCEL_IMPORT')" type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button v-if="checkBtnPermission('POINT_EXCEL_EXPORT')" type="danger" size="small" @click="handleExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="handleAddEmployee">新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" :index="indexMethod" width="100px" />
          <!-- <el-table-column label="头像" sortable="" prop="staffPhoto" /> -->
          <el-table-column label="头像" sortable="">
            <template #default="{row}">
              <img
                v-imgerror="errorImg"
                :src="row.staffPhoto ||defaultImg"
                alt=""
                class="img-wrip"
                @click="handleImgClick(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatFn" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <!-- prop永远是读取的列的字段名 -->
          <!-- 将来渲染的每一列内容,除了用prop渲染 -->
          <!-- <el-table-column label="入职时间" sortable="" prop="timeOfEntry" /> -->
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry |formatTime('YYYY/MM/DD') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button :disabled="!checkBtnPermission('POINT_USER_EDIT')" type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="handleRoleAssign(row.id)">角色</el-button>
              <el-button :disabled="!checkBtnPermission('POINT_USER_DELETE')" type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            :page-sizes="[1,2,3,4,5,6,7,8,9,10]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <AddEmployee :show-dialog.sync="isShow" @refresh="getUserList" />
      <!-- <el-dialog />在页面中第一次是懒渲染的 -->
      <el-dialog
        width="400px"
        title="二维码预览"
        :visible="showCode"
        @close="showCode=false"
      >
        <div style="text-align: center">
          <canvas ref="myCanvas" />
        </div>
      </el-dialog>

      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>

import { reqGetUserList, reqDelEmployee } from '@/api/employees'
import obj from '@/constant/employees'
import AddEmployee from './components/AddEmployee.vue'
import dayjs from 'dayjs'
import errorImg from '@/assets/common/bigUserHeader.png'
import Qrcode from 'qrcode'
import AssignRole from './components/assign-role.vue'
import ckeck from '@/mixins/check'
// canvas是专为复杂图像而生的,(echart)
//  Qrcode.toCanvas(图像的载体, 图像的信息)
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  mixins: [ckeck],
  data() {
    return {
      page: 1,
      size: 5,
      list: [],
      total: 0,
      loading: false,
      isShow: false,
      errorImg,
      defaultImg: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      showCode: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {

    handleAddEmployee() {
      if (!this.checkBtnPermission('POINT_USER_ADD')) {
        this.$message.error('你暂时没有该权限,请联系管理员')
        return
      }
      this.isShow = true
    },
    async getUserList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetUserList(this.page, this.size)
      // console.log(res)
      this.list = rows
      this.total = total
      this.loading = false
    },
    indexMethod(index) {
      return index + 1 + this.size * (this.page - 1)
    },
    handleCurrentChange(val) {
      this.page = val
      this.getUserList()
    },
    handleSizeChange(val) {
      this.size = val
      // 回到第一页(规范)
      this.page = 1
      this.getUserList()
    },
    formatFn(row, column, cellValue, index) {
      // 列的内容需要格式化:可以formatter=formatterfn
      // cellValer原来的值
      // return cellValue === 1 ? '正式工' : '临时工'
      const { hireType } = obj
      const res = hireType.find(item => item.id === +cellValue)
      return res ? res.value : '未知'
    },
    del(id) {
      this.$confirm('你确定要删除该员工嘛,此操作不可逆哦', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        this.$message.success('删除员工成功')
        // 能确定这个时间点,数据已经从数据库中删除了,但是本地还没更新(getUserList)
        if (this.list.length === 1) {
          this.page--
        }
        this.getUserList()
      }).catch(() => {
        console.log('取消')
      })
    },
    // 我们需要根据rows,header, headersRelations,转换成二维数组返回
    translList(rows, header, headersRelations) {
      // rows 决定了有多少小数组
      // headersArr 决定了小数组有多少项
      const res = []
      rows.forEach(item => {
        const arr = []
        header.forEach(key => {
          const englishKey = headersRelations[key]
          let val = item[englishKey]
          // 处理日期相关的数据
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            val = dayjs(val).format('YYYY年MM月DD日')
          }
          // 处理聘用形式数据
          if (englishKey === 'formOfEmployment') {
            const { hireType } = obj
            const resobj = hireType.find(v => v.id === +val)
            val = resobj ? resobj.value : '未知'
          }
          arr.push(val)
        })
        res.push(arr)
      })
      return res
    },

    async handleExport() {
      // 多表头
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 合并单元格
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const header = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { data: { rows }} = await reqGetUserList(1, this.total)
      const res = this.translList(rows, header, headersRelations)
      console.log(res)
      import('@/vendor/Export2Excel').then(excel => {
        console.log(excel)
        excel.export_json_to_excel({
          // 表格的表头
          header,
          // 表格的主体数据(固定格式->二维数组)
          data: res,
          filename: '员工信息表',
          autoWidth: true, // 宽度自适应 非必填
          bookType: 'xlsx', // 文件格式 非必填
          multiHeader,
          merges
        })
      })
    },
    handleImgClick(imgUrl) {
      if (!imgUrl) return
      this.showCode = true
      // 提前准备好二维码要承载的信息
      // console.log(imgUrl)
      this.$nextTick(() => {
      // 这个函数会在dom更新以后执行
        Qrcode.toCanvas(this.$refs.myCanvas, imgUrl)
      })
    },
    handleRoleAssign(id) {
      this.userId = id
      this.showRoleDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.img-wrip{
    width: 70px;
    height: 70px;
    border-radius: 50%;
}
</style>
